var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/school';

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

//登录判断
//用户名和密码变量名username,password
router.post('/login',function(req,res){
	var username = req.body.username;
	var password = req.body.password;
	
	var findData = function(db,callback){
		var conn = db.collection('user');
		var data = {username:username,password:password};

		conn.find(data).toArray(function(err,results){
			if(err){
				return;
			}
			callback(results);
		})
	}

	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
			console.log(err);
		}else{
			console.log("lianjiechang!!!!!!!!")
			findData(db,function(results){
				console.log(results+'lalalalla')
				if(results.length>0){

					//登录成功了以后，将用户名存储到session对象里面去，其它地方就可以使用了
					req.session.username = results[0].username;
					// res.send('login success');
					res.redirect('/');
				}else{
					//res.redirect('/login');
					res.send("cuola" + results)
				}

				db.close();
			})
		}
	})
});

//注册判断
router.post('/register',function(req,res){
	var username = req.body.username;
	var password = req.body.password;

	var insertData = function(db,callback){
		var conn = db.collection('user');
		var data=[{username:username,password:password}];
		conn.insert(data,function(err,results){
			if(err){
				return;
			}
			callback(results);
		});
	}

	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
			return;
		}else{
			insertData(db,function(results){
				res.send('注册成功');
				db.close();
			})
		}
	})
})


module.exports = router;
